#include "minidlnaplugin.h"
#include <QtPlugin>
#include <QApplication>
#include <QAction>
#include <QProgressDialog>

Q_EXPORT_PLUGIN2(minidlnaplugin, MiniDLNAPlugin)

MiniDLNAPlugin::MiniDLNAPlugin(QObject * parent)
    : QObject(parent)
{
    QDir::temp().mkpath("pio-dlna-plugin");
    m_basedir = QDir::temp();
    m_basedir.cd("pio-dlna-plugin");
    m_basedir.mkdir("files");
    clear();
}

MiniDLNAPlugin::~MiniDLNAPlugin()
{
    clear();
}

void MiniDLNAPlugin::setup(PioCore * core)
{
    m_core = core;
    m_action = new QAction(tr("share via DLNA"), this);
    m_action->setCheckable(true);
    connect(m_action, SIGNAL(triggered(bool)), this, SLOT(shareSelection(bool)));
    m_core->toolbar()->addAction(m_action);
}

QStringList MiniDLNAPlugin::licenseInfo()
{
    return QStringList()
            << "<p>The MiniDLNA plugin uses the program <i>minidlna</i>, which is l"
               "icensed under the terms of the GNU General Public License (G"
               "PL). The <i>minidlna</i> binary, its license and its source code is"
               " included in this software package. It can be obtained from "
               "<a href=\"http://sourceforge.net/projects/minidlna/\">http:/"
               "/sourceforge.net/projects/minidlna/</a> separately.</p>";
}

void MiniDLNAPlugin::shareSelection(bool share)
{
    clear();

    if(share) {
        QList<MediaItemPtr> sel = m_core->selection();
        QProgressDialog progress(tr("Preparing images..."), tr("Cancel"), 0, sel.size(), m_core->mainwindow());
        progress.setWindowModality(Qt::WindowModal);

        for(int i = 0; i < sel.size(); i++) {
            progress.setValue(i);
            if(progress.wasCanceled()) {
                m_action->setChecked(false);
                return;
            }
            QImage image = m_core->load(sel[i]->metadata().filename, QSize(1920, 1080));

            // save file
            image.save(QString("%1/files/file%2.jpg").arg(m_basedir.absolutePath()).arg(i, 5, 10, QChar('0')));
        }
        progress.setValue(sel.size());

        if(m_process.state() == QProcess::NotRunning) {
            QString pluginpath = qApp->applicationDirPath();
            QFile in(pluginpath + "/minidlna.conf");
            if(!in.open(QFile::ReadOnly))
                return;
            QString cfg = in.readAll();
            in.close();

            cfg.replace(QRegExp("port=[^\\n]*"), "port=8201");
            cfg.replace(QRegExp("network_interface=[^\\n]*"), "network_interface=wlan0");
            cfg.replace(QRegExp("media_dir=[^\\n]*"), "media_dir=" + m_basedir.absoluteFilePath("files"));
            cfg.replace(QRegExp("friendly_name=[^\\n]*"), "friendly_name=Photographers Image Organizer");

            QString configpath = m_basedir.absoluteFilePath("minidlna.conf");
            QFile out(configpath);
            if(!out.open(QFile::WriteOnly))
                return;
            out.write(cfg.toLocal8Bit());
            out.close();

            QString cmd = pluginpath + "/minidlna";
            QProcess::execute(QString("chmod +x \"%1\"").arg(cmd));
            m_process.start(cmd, QStringList() << "-R" << "-d" << "-f" << configpath);
        }
    }
}

void MiniDLNAPlugin::clear()
{
    if(m_process.state() != QProcess::NotRunning) {
        m_process.terminate();
        if(!m_process.waitForFinished(5000)) {
            m_process.kill();
            m_process.waitForFinished(5000);
        }
    }

    QDir d = m_basedir;
    d.cd("files");
    QStringList files = d.entryList(QDir::Files);
    foreach(QString f, files) {
        QFile::remove(d.absoluteFilePath(f));
    }
}
